package org.dark.fund.aspect;

import lombok.extern.slf4j.Slf4j;
import org.dark.fund.common.ApiResult;
import org.dark.fund.exceptions.FundBizException;
import org.dark.fund.exceptions.FundSysException;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.sql.SQLException;

@Slf4j
@RestControllerAdvice
public class FundExceptionAop implements ResponseBodyAdvice<Object> {

    @ExceptionHandler
    @ResponseStatus(HttpStatus.OK)
    public ApiResult<?> exception(Exception exception) {
        ApiResult result = null;
        if (exception instanceof FundBizException) {
            log.info("业务异常: ", exception);
            result = ApiResult.fundException((FundBizException) exception);
        } else if (exception instanceof FundSysException) {
            log.error("系统异常: ", exception);
            result = ApiResult.fundException((FundBizException) exception);
        } else if (exception instanceof SQLException) {
            log.error("数据库异常: ", exception);
            result = ApiResult.exception(exception);
        } else {
            log.error("未知系统异常: ", exception);
            result = ApiResult.exception(exception);
        }
        return result;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object result, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info("result [{}], methodParam [{}], mediaType [{}], class [{}]", result, methodParameter, mediaType, aClass);
        return result;
    }
}
